﻿using DotNetCore.CAP;
using DotNetCore.CAP.Serialization;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using VIP.Data;
using VIP.Data.EFProvider;
using VIP.Data.Entities;
using VIP.Events.Order;
using VIP.Infrastructure.Serializer;

namespace VIP.Domain.Subscribers
{
    public interface IOrderSubscriberService { }
    /// <summary>
    /// 订单事件订阅器
    /// </summary>
    public class OrderSubscriberService : IOrderSubscriberService, ICapSubscribe
    {
        private readonly IUnitOfWork<VIPDbContext> _unitOfWork;
        private readonly ILogger<OrderSubscriberService> _logger;
        private readonly Infrastructure.Serializer.ISerializer _serializer;

        public OrderSubscriberService(IUnitOfWork<VIPDbContext> unitOfWork, ILogger<OrderSubscriberService> logger, Infrastructure.Serializer.ISerializer serializer)
        {
            _unitOfWork = unitOfWork;
            _logger = logger;
            _serializer = serializer;
        }

        [CapSubscribe(nameof(OrderCreated))]
        public Task CreateOrder(OrderCreated @event)
        {
            var orderRep = _unitOfWork.GetRepositoryAsync<Order>();
            var orderItemRep = _unitOfWork.GetRepositoryAsync<OrderItem>();

            orderRep.AddAsync(@event.Order);
            orderItemRep.AddAsync(@event.Items);

            var rel = _unitOfWork.SaveChanges();
            return Task.CompletedTask;
        }
        [CapSubscribe(nameof(OrderItemAdded))]
        public Task AddOrderItem(OrderItemAdded @event)
        {
            var orderItemRep = _unitOfWork.GetRepositoryAsync<OrderItem>();

            orderItemRep.AddAsync(@event.Item);

            var rel = _unitOfWork.SaveChanges();
            return Task.CompletedTask;
        }

        [CapSubscribe(nameof(OrderCreated))]
        public Task CreateOrder_SendMessage(OrderCreated @event)
        {
            _logger.LogInformation(_serializer.Serialize(@event));
            _logger.LogError(_serializer.Serialize(@event));
            return Task.CompletedTask;
        }
    }
}
